package com.topnav.mc.sse;


import com.js.lib.cache.LocalCache;
import com.js.lib.cache.SysCache;
import com.js.lib.result.Result;
import com.js.lib.task.Task;
import com.topnav.mc.admin.security.PermissionGrade;
import com.topnav.mc.common.Constant;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Api(value = "sse", tags = "消息推送管理")
@CrossOrigin
@RestController
@RequestMapping("sse")
@Slf4j
public class SseController {
    @Autowired
    private SysCache sysCache;

    /**
     * 浏览器客户端订阅消息
     * SSE 推送
     * @param clientId
     * @return
     */
    @ApiOperation(value = "客户端订阅消息")
    @ApiImplicitParams(
            {@ApiImplicitParam(name="browserId", value = "浏览器ID", required=false,dataTypeClass = String.class)})
    @GetMapping("/emit")
    public SseEmitter emit(@RequestParam String clientId,String token) throws Exception{
        if (StringUtils.isEmpty(clientId)){
            throw new Exception("clientId 必须提供！");
        }
        //取当前用的权限
        //String token = MDC.get(Constant.MDC_TOEKN);
        EmitterBean emitterBean = (EmitterBean)sysCache.hget(Constants.CAHCE_SSE_CLIENT,clientId);
        if (emitterBean != null){
            emitterBean.setToken(token);
            return emitterBean.getEmitter();
        }else{
            SseEmitter sseEmitter = new SseEmitter(0L);
            //给客户端发送断开重连时间
            sseEmitter.send(SseEmitter.event().reconnectTime(10000).data(Result.ok("连接成功")));
            sseEmitter.onTimeout(() -> {
                log.info("sseEmitter.id: {}超时",clientId);
                //sysCache.remove(clientId);
                sseEmitter.onTimeout(sseEmitter::complete);
            });
            sseEmitter.onCompletion(()->{
                log.info("sseEmitter:{} 信息发送完成",clientId);
                sseEmitter.complete();
                sysCache.hdel(Constants.CAHCE_SSE_CLIENT,clientId,new EmitterBean(token,sseEmitter));
            });
            sseEmitter.onError((throwable) ->  {
                sseEmitter.complete();
                sysCache.hdel(Constants.CAHCE_SSE_CLIENT,clientId,new EmitterBean(token,sseEmitter));
            });

            //保存到缓存，加token 为了取得权限
            sysCache.hset(Constants.CAHCE_SSE_CLIENT,clientId,new EmitterBean(token,sseEmitter));
            return sseEmitter;
        }

    }

}
